package com.shawn.baseappbygroovydsl.ui.extension

import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import android.view.Gravity
import android.widget.Toast
import com.shawn.baseappbygroovydsl.MainActivity
import com.shawn.baseappbygroovydsl.base.AppBase

/**
 * 描述：
 * 作者： shawn
 * 时间： 2024/8/1910:03
 */
object ExtensionCommon {
    val Float.dp
        get() = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this,
            Resources.getSystem().displayMetrics
        )


    val Float.sp
        get() = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            this,
            Resources.getSystem().displayMetrics
        )

    fun Float.dp2px(): Int {
        val scale = AppBase.instance.resources?.displayMetrics?.density ?: 1f
        return (this * scale + 0.5f).toInt()
    }

    fun Float.px2dp(): Int {
        val scale = AppBase.instance.resources?.displayMetrics?.density ?: 1f
        return (this / scale + 0.5f).toInt()
    }

    fun Context.deviceWidth() = this.resources.displayMetrics.widthPixels

    fun Context.deviceHeight() = this.resources.displayMetrics.heightPixels

    fun String.toast(timeLong: Boolean = false) {
        if (timeLong) {
            Toast.makeText(AppBase.instance, this, Toast.LENGTH_LONG).apply {
                setGravity(Gravity.CENTER, 0, 0)
                show()
            }
        } else {
            Toast.makeText(AppBase.instance, this, Toast.LENGTH_SHORT).apply {
                setGravity(Gravity.CENTER, 0, 0)
                show()
            }
        }
    }

    fun String.appToastV2(context: Context?){
        if(context is MainActivity){
            context.showAppToast(this)
        }
    }
}